package com.cw.async.callback;

import java.util.concurrent.Executors;

import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.MoreExecutors;

/**
 * 使用guava实现异步回调 {@link java.util.concurrent.Future}
 * {@link com.google.common.util.concurrent.ListenableFuture}
 * {@link com.google.common.util.concurrent.FutureCallback}
 *
 * @author landon
 */
public class GuavaCallback {
    public static void main(String[] args) {

        // 除了ListenableFuture,guava还提供了FutureCallback接口,相对来说更加方便一些.
        ListeningExecutorService guavaExecutor2 = MoreExecutors.listeningDecorator(Executors.newSingleThreadExecutor());
        final ListenableFuture<String> listenableFuture2 = guavaExecutor2.submit(() -> {
            Thread.sleep(1000);
            System.out.println("asyncThreadName:" + Thread.currentThread()
                .getName());
            return "this is guava future call.support async callback using FutureCallback";
        });
        // 注意这里没用指定执行回调的线程池,从输出可以看出，默认是和执行异步操作的线程是同一个.
        Futures.addCallback(listenableFuture2, new FutureCallback<String>() {

            @Override
            public void onSuccess(String result) {
                System.out.println("async callback(using FutureCallback) result:" + result);
                System.out.println("execute callback threadName:" + Thread.currentThread()
                    .getName());
            }

            @Override
            public void onFailure(Throwable t) {
            }
        }, Executors.newSingleThreadExecutor());
    }
}